package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void removeById(Long id) {
        //判断该分类下是否有菜品或者套餐
        //根据分类的id在菜品表里查找
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getCategoryId ,id);
        Integer count1 = dishMapper.selectCount(lambdaQueryWrapper);

        if(count1 > 0){
            //代表该分类id下有菜品.抛个异常
            throw new CustomException("分类下已有菜品，请先删除对应菜品");
        }
        //根据分类的id在套餐表里查找
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        Integer count2 = setmealMapper.selectCount(setmealLambdaQueryWrapper);


        if(count2 > 0){
            //代表该分类id下有套餐,抛个异常
            throw new CustomException("分类下已有套餐，请先删除对应套餐");
        }

        //说明该分类id下什么关联数据也没有,可以直接删
        super.removeById(id);
    }
}
